package com.hongyi.modelcontest.modular.contest.controller;


import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hongyi.modelcontest.core.common.exception.BizExceptionEnum;
import com.hongyi.modelcontest.core.util.AuthCode;
import com.hongyi.modelcontest.core.util.COSUtils;
import com.hongyi.modelcontest.core.util.IdUtil;
import com.hongyi.modelcontest.modular.contest.entity.CustomerInfo;
import com.hongyi.modelcontest.modular.contest.mapper.CustomerInfoMapper;
import com.hongyi.modelcontest.modular.contest.service.RecordService;
import com.hongyi.modelcontest.modular.contest.vo.ContestRegister;
import com.hongyi.modelcontest.modular.contest.vo.DeptVo;
import com.hongyi.modelcontest.modular.contest.vo.DeptVoDto;
import com.hongyi.modelcontest.modular.contest.vo.ParnterVo;
import com.hongyi.modelcontest.modular.system.entity.Dept;
import com.hongyi.modelcontest.modular.system.entity.User;
import com.hongyi.modelcontest.modular.system.service.DeptService;
import com.hongyi.modelcontest.modular.system.service.UserService;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 客户信息表 前端控制器
 * </p>
 *
 * @author skyet
 * @since 2019-02-23
 */
@Controller
@RequestMapping("/cus")
public class CustomerInfoController extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(CustomerInfoController.class);

    @Resource
    private UserService userService;

    @Resource
    private RecordService recordService;

    @Resource
    private CustomerInfoMapper customerInfoMapper;
    @Resource
    private AuthCode authCode;
    @Resource
    private DeptService deptService;


    /**
     * 根据openId获取用户信息
     */
    @GetMapping("/list")
    @ResponseBody
    public ResponseData list() {
        return ResponseData.success(recordService.listVo());
    }


    /**
     * 根据openId获取用户信息
     */
    @GetMapping("/agent")
    @ResponseBody
    public ResponseData agent(@RequestParam("openId") String openId) {
        Map<String, Object> map = new HashMap<>(4);
        User user = userService.getByOpenId(openId);
        if (user != null) {
            map.put("agentId", user.getUserId());
            Dept dept = deptService.getById(user.getDeptId());
            if (dept != null) {
                DeptVoDto vo = getDeptVoDto(dept);
                map.put("dept", vo);
            }
        }
        CustomerInfo customerInfo = customerInfoMapper.selectOne(new QueryWrapper<CustomerInfo>().lambda().eq(CustomerInfo::getWechatOpenid, openId));

        if (customerInfo != null) {
            map.put("customerId", customerInfo.getCustomerId());
        }

        return ResponseData.success(map);
    }

    @GetMapping("/dept")
    @ResponseBody
    public ResponseData dept(@RequestParam("deptId") String deptId) {
        Dept dept = deptService.getById(deptId);
        if (dept == null) {
            throw new ServiceException(500, "获取代理商信息失败，deptId错误");
        }
        if (StringUtils.isEmpty(dept.getLogo())) {
            String logo = getParentLogo(dept.getPid());
            dept.setLogo(logo);
        }
        if (StringUtils.isEmpty(dept.getQrCode())) {
            String logo = getParentQrCode(dept.getPid());
            dept.setQrCode(logo);
        }
        DeptVoDto vo = getDeptVoDto(dept);
        return ResponseData.success(vo);
    }

    private String getParentQrCode(Long pid) {
        Dept pd = deptService.getById(pid);
        if (pd != null) {
            if (!StringUtils.isEmpty(pd.getQrCode())) {
                return pd.getQrCode();
            } else {
                return getParentLogo(pd.getPid());
            }
        }
        return null;
    }

    private String getParentLogo(Long pid) {
        Dept pd = deptService.getById(pid);
        if (pd != null) {
            if (!StringUtils.isEmpty(pd.getLogo())) {
                return pd.getLogo();
            } else {
                return getParentLogo(pd.getPid());
            }
        }
        return null;
    }

    private DeptVoDto getDeptVoDto(Dept dept) {
        DeptVoDto vo = new DeptVoDto();
        BeanUtils.copyProperties(dept, vo);
        vo.setDeptId(dept.getDeptId() + "");
        ParnterVo parentVo = new ParnterVo();
        Dept parent;
        if (dept.getPid() > 10001) {
            parent = getParent(dept.getPid());
        } else {
            parent = dept;
        }
        if (parent != null) {
            parentVo.setTitle(parent.getTitle());
            parentVo.setDesc(parent.getDescription());
            String assist = parent.getAssist();
            if (!StringUtils.isEmpty(assist)) {
                String[] logos = assist.split(";");
                parentVo.setAssistLogo(Arrays.asList(logos));
            } else {
                parentVo.setAssistLogo(Collections.emptyList());
            }
            parentVo.setLogo(parent.getLogo());
            vo.setParnter(parentVo);
        }
        vo.setParnter(parentVo);
        return vo;
    }

    private Dept getParent(Long pid) {
        Dept pd = deptService.getById(pid);
        if (pd != null) {
            if (pd.getPid() <= 10001L) {
                return pd;
            } else {
                return getParent(pd.getPid());
            }
        }
        return null;
    }


    /**
     * 报名
     */
    @PostMapping("/register")
    @ResponseBody
    public ResponseData register(@RequestBody @Valid ContestRegister contestRegister, BindingResult result) {
        if (result.hasErrors()) {
            logger.error("数据错误:{}", result.toString());
            throw new ServiceException(BizExceptionEnum.REQUEST_INVALID_PARAMETER);
        }
        User user = userService.getById(contestRegister.getAgentId());
        if (user == null) {
            contestRegister.setAgentId("0");
        }
        return ResponseData.success(recordService.register(contestRegister));
    }

    /**
     * 获取报名详情
     */
    @GetMapping("/detail")
    @ResponseBody
    public ResponseData detail(@RequestParam("openId") String openId,
                               @RequestParam("contestId") String contestId) {
        return ResponseData.success(recordService.detail(openId, contestId));
    }

    /**
     * 供应商注册
     */
    @PostMapping("/binding")
    @ResponseBody
    public ResponseData detail(@RequestBody @Valid DeptVo deptVo, BindingResult result) {
        if (result.hasErrors()) {
            throw new ServiceException(BizExceptionEnum.REQUEST_INVALID_PARAMETER);
        }
        Map<String, Long> map = new HashMap<>();
        map.put("agentId", recordService.saveDept(deptVo));
        return ResponseData.success(map);
    }

    /**
     * 获取手机验证码
     */
    @GetMapping("/code")
    @ResponseBody
    public ResponseData code(@RequestParam("phone") String phone) {
        authCode.sendCode(phone);
        return ResponseData.success();
    }

    /**
     * 上传图片
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:44
     */
    @RequestMapping(method = RequestMethod.POST, path = "/upload")
    @ResponseBody
    public ResponseData upload(@RequestPart("file") MultipartFile picture) {
        if (picture != null && picture.getSize() > 0) {
            if (ContentType.IMAGE_JPEG.getMimeType().equals(picture.getContentType()) ||
                    ContentType.IMAGE_PNG.getMimeType().equals(picture.getContentType()) ||
                    ContentType.IMAGE_GIF.getMimeType().equals(picture.getContentType())) {
                return ResponseData.success(COSUtils.uploadPhoto("LO" + IdUtil.getId(), picture));
            } else {
                return ResponseData.error("图片格式错误！");
            }
        }
        return ResponseData.error("图片不能为空！");
    }

    /**
     * 查看图片
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:44
     */
    @RequestMapping("/picture")
    public void downloadPicture(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        COSObject obj = COSUtils.dowloadPhoto(fileName);
        downloadFile(obj, response);
    }

    /**
     * 上传图片
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:44
     */
    @RequestMapping(method = RequestMethod.POST, path = "/uploadLogo")
    @ResponseBody
    public ResponseData uploadLogo(@RequestPart("file") MultipartFile[] pictures) {
        if (pictures != null && pictures.length > 0) {
            String[] lists = new String[pictures.length];
            for (int i = 0; i < pictures.length; i++) {
                MultipartFile picture = pictures[i];
                if (ContentType.IMAGE_JPEG.getMimeType().equals(picture.getContentType()) ||
                        ContentType.IMAGE_PNG.getMimeType().equals(picture.getContentType()) ||
                        ContentType.IMAGE_GIF.getMimeType().equals(picture.getContentType())) {
                    String key = COSUtils.uploadLogo("LO" + IdUtil.getId(), picture);
                    lists[i] = key;
                } else {
                    return ResponseData.error("图片格式错误！");
                }
            }
            return ResponseData.success(StringUtils.arrayToDelimitedString(lists, ";"));

        }
        return ResponseData.error("图片不能为空！");
    }

    /**
     * 查看logo
     *
     * @author fengshuonan
     * @Date 2018/12/24 22:44
     */
    @RequestMapping("/logo")
    public void downloadLogo(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        COSObject obj = COSUtils.dowloadLogo(fileName);
        downloadFile(obj, response);
    }


    private void downloadFile(COSObject obj, HttpServletResponse response) {
        try {
            COSObjectInputStream in = obj.getObjectContent();
            response.setContentType(obj.getObjectMetadata().getContentType());
            ServletOutputStream sos = response.getOutputStream();
            byte[] b = new byte[1024];
            int n;
            int len = 0;
            while ((n = in.read(b)) != -1) {
                len += n;
                sos.write(b, 0, n);
            }
            response.setContentLength(len);
            in.close();
            sos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

